package top.lyjwn.todo.weinxin.applet.controller;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import top.lyjwn.todo.aop.log.controller.ControllerLog;
import top.lyjwn.todo.aop.token.ExemptToken;
import top.lyjwn.todo.common.template.R;
import top.lyjwn.todo.weinxin.api.applet.AuthCode2Session;
import top.lyjwn.todo.weinxin.applet.service.WXAUserService;
import top.lyjwn.todo.weinxin.data.applet.Code2Session;
import top.lyjwn.todo.weinxin.data.applet.WXAUser;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 微信小程序用户控制器
 *
 * @author luoyujie
 */
@RestController
@RequestMapping("/wxa/user")
public class WXAUserController {

    private static final Logger log = LoggerFactory.getLogger("info");

    @Autowired(required = false)
    private WXAUserService wxaUserService;

    @Autowired
    private AuthCode2Session authCode2Session;


    /**
     * 登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程
     *
     * @param code
     * @return
     */
    @ExemptToken
    @ControllerLog(description = "登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程")
    @RequestMapping(value = "/code2Session", method = RequestMethod.POST)
    public R<Map<String, Object>> code2Session(String code, WXAUser wxaUser) {
        JSONObject responseToJSON = authCode2Session.getResultJSONObject(code);
        // 响应 数据
        R<Map<String, Object>> template;
        Code2Session code2Session = Code2Session.builder(responseToJSON);
        if (code2Session != null
                && (code2Session.getErrcode() == null || "OK".equals(code2Session.getErrcode().toUpperCase())) ) {
            template = R.init().ok("校验成功");
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("code2Session", code2Session);
            if (wxaUserService != null) {
                if (wxaUserService.existsByOpenid(code2Session.getOpenid())) {
                    map.put("token", wxaUserService.getToken(code2Session.getOpenid()));
                } else {
                    R<String> register = wxaUserService.register(code2Session.getOpenid(), wxaUser, code2Session.getUnionid());
                    if (register.isDone()){
                        map.put("token",register.getData() );
                    }else{
                        template.setDone(register.isDone());
                        template.setCode(register.getCode());
                        template.setMsg(register.getMsg());
                    }
                }
            }
            template.setData(map);
        } else {
            template = R.init().error(500, "校验失败");
        }
        return template;
    }
}
